import { message, Modal, Table } from 'antd';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import positionService from '@/api/services/security/positionService';
import { hasPermission } from '@/utils/permission';

import { PositionType } from '../position/type';
import { SearchForm } from '../role/search-form';

import { ListData, ModalProps, UserInfo } from '#/entity';

export function UserPositionModal({ show, onOk, onCancel, formValue }: ModalProps<UserInfo>) {
  const [tableData, setTableData] = useState<ListData<PositionType>>();
  const [searchForm, setSearchForm] = useState<SearchForm>({
    take: 10,
    page: 1,
  });
  useEffect(() => {
    if (show) {
      setSearchForm({ take: 10, page: 1 });
    }
  }, [show]);
  useEffect(() => {
    // 获取所有的岗位
    if (hasPermission('DEPARTMENT:DEPARTMENT:READ')) {
      positionService.getPositionsList({ ...searchForm }).then((res) => {
        setTableData(res);
      });
    }
  }, [searchForm]);
  useEffect(() => {
    // 初始化选中岗位
    if (formValue.meta.POSITION) {
      setSelectedRowKeys(
        formValue.meta.POSITION.map((item: { code: string }) => {
          return item.code;
        }),
      );
    }
  }, [formValue]);
  const columns = [
    {
      title: '岗位名称',
      dataIndex: 'name',
      key: 'name',
    },
  ];
  // 选中的角色列表
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const rowSelection: TableRowSelection<PositionType> = {
    hideSelectAll: true,
    selectedRowKeys,
    // onChange: onSelectChange,
    onSelect: (record: PositionType, selected: boolean) => {
      if (selected) {
        positionService
          .userAddPosition({
            positionCode: record.code,
            userId: formValue.id,
            operator: 'ADD',
          })
          .then((_) => {
            message.success(`为用户 ${formValue.name || ''} 添加岗位 ${record.name} 成功`);
          });
        setSelectedRowKeys([...selectedRowKeys, record.code]);
      } else {
        positionService
          .userAddPosition({
            positionCode: record.code,
            userId: formValue.id,
            operator: 'REMOVE',
          })
          .then((_) => {
            message.success(`为用户 ${formValue.name || ''} 删除岗位 ${record.name} 成功`);
          });
        setSelectedRowKeys(selectedRowKeys.filter((item) => item !== record.code));
      }
    },
  };
  return (
    <Modal
      okText="确定"
      title={`为用户 ${formValue.name || ''} 添加岗位`}
      open={show}
      onOk={onOk}
      onCancel={onCancel} // 隐藏取消按钮,但是保留取消功能
      cancelButtonProps={{ style: { display: 'none' } }}
      maskClosable
      keyboard
    >
      <Table
        rowKey="code"
        rowSelection={rowSelection}
        dataSource={tableData?.data}
        columns={columns}
        size="small"
        pagination={{
          current: searchForm.page,
          pageSize: searchForm.take,
          total: tableData?.count, // 新增：总条目数
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, size) => {
            setSearchForm((prev) => ({ ...prev, page, take: size }));
          },
        }}
      />
    </Modal>
  );
}
